const { Service } = require('egg');
const moment = require('moment');
const permission_table = 'permission';
const user_table = 'user';
const { v4: uuidV4 } = require('uuid');


class PermissionsService extends Service {

  // 查询权限列表
  async list(name, key, url, order, method, pageIndex = 1, pageSize = 10) {
    try {
      let promiseData = this.app.knex().select('t1.uuid', 't1.name', 't1.key',
        't1.create_time', 't2.name as create_by', 't1.update_time', 't3.name as update_by')
        .from(`${permission_table} as t1`)
        .leftJoin(`${user_table} as t2`, () => {
          this.on('t2.uuid', '=', 't1.create_by');
        })
        .leftJoin(`${user_table} as t3`, () => {
          this.on('t3.uuid', '=', 't1.update_by');
        });

      let promiseCount = await this.app.knex(permission_table).count({ id: 'uuid' });

      if (name) {
        promiseData = promiseData.whereLike('t1.name', `%${name}%`);
        promiseCount = promiseCount.whereLike('name', `%${name}%`);
      }

      if (key) {
        promiseData = promiseData.whereLike('t1.key', `%${key}%`);
        promiseCount = promiseCount.whereLike('key', `%${key}%`);
      }

      if (url) {
        promiseData = promiseData.whereLike('t1.url', `%${url}%`);
        promiseCount = promiseCount.whereLike('url', `%${url}%`);
      }

      promiseData = promiseData.orderBy(order, method).limit(Number(pageSize)).offset((Number(pageIndex - 1) * Number(pageSize)));

      const list = await promiseData;

      const count = await promiseCount;

      return {
        count: count.id,
        list,
      };
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 新增
  async insert(name, key, url, type, parent_id = '0') {
    try {
      const time = moment();
      const { id } = this.ctx.session;

      const is_key_repeat = await this.app.knex().select('*').from(permission_table)
        .where({ key });

      const is_url_repeat = await this.app.knex().select('*').from(permission_table)
        .where({ url });

      if (is_key_repeat) {
        throw new Error('当前key存在');
      }


      if (is_url_repeat) {
        throw new Error('当前url存在');
      }

      const instance = {
        uuid: uuidV4(),
        name, key, url, parent_id,
        create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
        update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
        create_by: id,
        update_by: id,
        type: Number(type),
      };

      const data = await this.app.knex(permission_table).insert(instance).returning('id');
      instance.id = data[0];

      return instance;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 更新
  async update(name, key, url, uuid) {
    try {
      const time = moment();
      const instance = await this.app.knex().select('*').from(permission_table)
        .where({ uuid });
      if (name) {
        instance.name = name;
      }

      if (key) {

        const is_key_repeat = await this.app.knex().select('*').from(permission_table)
          .where({ key })
          .whereNot({ uuid });

        if (is_key_repeat) {
          throw new Error('当前key存在');
        }

        instance.key = key;
      }

      if (url) {

        const is_url_repeat = await this.app.knex().select('*').from(permission_table)
          .where({ url })
          .whereNot({ uuid });

        if (is_url_repeat) {
          throw new Error('当前url存在');
        }

        instance.url = url;
      }

      instance.update_time = moment(time).format('YYYY-MM-DD HH:mm:ss');

      return instance;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 删除
  async delete(ids) {
    try {
      const time = moment();
      const { id } = this.ctx.session;
      await this.app.knex(permission_table)
        .update({ is_delete: 1, update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'), update_by: id })
        .whereIn('uuid', ids)
        .andWhere({ is_delete: 0 });

      return;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }
}

module.exports = PermissionsService;
